<template>
	<view class="BigBreak" :styles="{ height: pageH }">
		<image class="bgi" :src="imgPath + 'bigBreak/bg2.png'" :style="{ height: bgH + 'px' }" mode=""></image>
		<view class="title-box" :style="{ 'padding-top': inf0Pt + 'vh' }">
			<image class="back" @click="back" :src="imgPath + 'AICont/back-arrow.svg'" mode=""></image>
			<view class="title"></view>
			<view class="back"></view>
		</view>
		<view class="main">
			<view class="cont-list">
				<view :class="['item']" v-for="(item, index) in tipsList" :key="index">
					<view class="title" @tap="openTipsPopup(item, index)">
						{{ item.title }}
					</view>
					<view class="cont-main" v-if="item.id == 4">
						<view class="textarea-box" @tap.stop="">
							<!-- #ifndef MP-WEIXIN -->
							<textarea :adjust-position="false" class="cont-textarea" :auto-blur="true" :value="content" :maxlength="2000" @blur="contentBlur" placeholder="请粘贴链接" @tap.stop="textareaTap" @input="contentWatch_web" @focus="contentFocus" />
							<!-- #endif -->
							<!-- #ifdef MP-WEIXIN -->
							<textarea :adjust-position="false" class="cont-textarea" :auto-blur="true" :value="content" :maxlength="2000" @blur="contentBlur" placeholder="请粘贴链接" @tap.stop="textareaTap" @input.native="contentWatch_wx" @focus="contentFocus" />
							<!-- #endif -->
						</view>
						<view class="btns">
							<view class="btns-item style1" @tap.stop="getClipboardData">粘贴链接</view>
							<view class="btns-item style2" :style="{ filter: content ? 'brightness(1)' : 'brightness(0.5)' }" @tap.stop="submit">提取文案</view>
						</view>
					</view>
				</view>
			</view>
			<view class="main-tips">请自觉遵守平台链接导入规范</view>
		</view>

		<uni-popup ref="tipsPopup" type="dialog">
			<uni-popup-dialog mode="base" title="温馨提示" :confirmText="'确定'" :showClose="true" @confirm="tapFN(tipsList[tipsListInd])">
				<view class="tips" style="color: #000" v-if="tipsListInd == 0">从系统相册选择{{ tipsListInd == 0 ? "视频文件" : "音频文件" }}</view>
				<!-- #ifdef MP-WEIXIN -->
				<view class="tips" style="color: #000" v-if="tipsListInd == 1">从微信聊天记录选择{{ tipsListInd == 0 ? "视频文件" : "音频文件" }}</view>
				<!-- #endif -->

				<!-- #ifdef H5 -->
				<view class="tips" style="color: #000" v-if="tipsListInd == 1">从系统文件选择{{ tipsListInd == 0 ? "视频文件" : "音频文件" }}</view>
				<!-- #endif -->
			</uni-popup-dialog>
		</uni-popup>
		<LoginDialog ref="LoginDialog" :show="LoginDialogShow" @successFn="loginDialogShowSucc" @changeShow="changeLoginDialogShow" style="z-index: 999"></LoginDialog>
	</view>
</template>

<script>
import { tools } from "@/utils/util.js";
import myRequest, * as request from "@/utils/api.js";
import * as api from "@/api/createVideo.js";
let contentWatchTimer = null;
export default {
	name: "BigBreak",
	data() {
		return {
			imgPath: tools.imgPath,
			inf0Pt: 0,
			systemInfo: {},
			webStyle: {
				height: ""
			},
			pageH: "",
			keyboardH: 0,
			LoginDialogShow: false,
			pageInfo: {},

			bgH: 0,
			content: "",
			tipsListInd: -1,
			tipsList: [
				{
					id: 1,
					title: "相册视频文案提取",
					cont: ``,
					fnName: "getImage"
				},
				// #ifndef APP
				{
					id: 2,
					title: "本地音频文案提取",
					cont: ``,
					fnName: "getAudio"
				},
				// #endif
				{
					id: 3,
					title: "视频背景音乐提取",
					cont: ``,
					fnName: "noFn"
				},
				{
					id: 4,
					title: "链接文案提取",
					cont: ``
				}
			]
		};
	},
	methods: {
		// 获取系统info
		initSystemInfo(isUpdate = true) {
			const that = this;
			return new Promise((resolve, reject) => {
				uni.getSystemInfo({
					success(payload) {
						if (isUpdate) {
							that.systemInfo = payload;
							that.webStyle.height = `${that.systemInfo.windowHeight}px`;
							that.bgH = `${that.systemInfo.windowHeight}`;
							console.log("initSystemInfo", that.systemInfo);
							switch (that.systemInfo.uniPlatform) {
								case "web":
									that.inf0Pt = 4.5;
									break;
								case "app":
									that.inf0Pt = 4.5;
									break;
								case "mp-weixin":
									that.inf0Pt = 4.5;
									break;
							}
						}
						resolve(payload);
					}
				});
			});
		},
		// 跳转页面
		toPage(path, type = "navigateTo") {
			uni[type]({
				url: path
			});
		},
		// 回退
		back() {
			let pages = getCurrentPages();
			if (pages.length > 1) {
				uni.navigateBack({
					delta: 1
				});
			} else {
				uni.setStorageSync("toHome", {
					footerBarListAc: 1
				});
				uni.reLaunch({
					url: "/pages/index/index"
				});
			}
		},
		// 获取页面参数
		initPageInfo(opt) {
			// let pageInfo = uni.getStorageSync("AIContInfo");
			// this.pageInfo = pageInfo;
			// uni.removeStorageSync("AIContInfo");
		},
		// 监听登录弹出层显示
		changeLoginDialogShow(val) {
			this.LoginDialogShow = val;
		},
		// 登陆成功数据刷新
		loginDialogShowSucc() {
			this.getData();
		},
		// 获取数据
		getData() {},
		openTipsPopup(item, index) {
			this.tipsListInd = index;
			if (item.id == 3) {
				this.noFn();
				return;
			}
			if (item.id != 3) {
				this.$refs.tipsPopup.open();
			}
		},
		// 动态事件
		tapFN(item, index) {
			let fnName = item.fnName;
			let args = item.args || [];
			if (fnName && this[fnName] && typeof this[fnName] === "function") {
				this[fnName](...args);
			}
		},
		downloadBg() {
			uni.showLoading({
				title: "请稍后"
			});

			uni.downloadFile({
				url: this.imgPath + "bigBreak/bg.png",
				success(res) {
					console.log(res);
					uni.hideLoading();
				}
			});
		},
		// 相册视频文案提取
		getImage() {
			const that = this;
			let extension = ["avi", "mp4", ".mkv", "mov", "flv", "rmvb", "3gp"];
			// uni.chooseFile({
			// uni.chooseMessageFile({
			// 	count: 1, //默认100
			// 	type: "video",
			// 	extension: extension,
			uni.chooseVideo({
				sourceType: ["album", "camera"],
				maxDuration: 30,
				compressed: false,
				camera: "front",
				success: async (res) => {
					console.log(res);
					const tempFilePaths = res.tempFilePaths;
					let file = res.tempFilePath;
					// if (!file.type.includes("video")) {
					// 	return tools.easyToast("请选择视频频文件！");
					// }
					let name = tools.createID() + res.tempFilePath.slice(res.tempFilePath.lastIndexOf("."));
					// if (!/^[\u4e00-\u9fa5a-zA-Z0-9\.\-]+$/.test(name)) {
					// 	return tools.easyToast("文件名不能包含符号，只能是文字或数字");
					// }
					// if (file.size / 1024 / 1024 > this.uploadFileSize) {
					// 	return tools.easyToast(`文件大小超过${this.uploadFileSize}M!`);
					// }
					uni.showLoading({
						title: "上传中"
					});
					let ossData = await api.postOSS({
						reqType: "",
						matName: name,
						payLoad: {}
					});
					uni.hideLoading();
					uni.showLoading({
						title: "上传中"
					});
					let ress = await that.wx_getOSSApi_new(ossData, res.tempFilePath, name);
					console.log(ress);
					if (!ress) return tools.easyToast("解析失败！");
					uni.hideLoading();
					uni.showLoading({
						title: "视频解析中"
					});
					let result = await api.getAiworkobjv1ct({
						content: ress.src,
						obj: "v_obj"
					});
					uni.hideLoading();
					console.log(result);
					uni.setStorageSync("bigBreakEditInfo", {
						content: result.data
					});
					this.toPage("/pages/bigBreakEdit/bigBreakEdit");
				},
				fail(err) {
					console.log(err);
				}
			});
		},
		// 本地音频文案提取
		async getAudio() {
			const that = this;
			let extension = ["wav", "mp3", "aac", "m4a",  "ogg", "3gpp"];
			extension = extension.reduce((p, e) => {
				p.push(e);
				p.push(e.toLocaleUpperCase());
				return p;
			}, []);

			let res = await new Promise((next) => {
				// #ifdef H5
				uni.chooseFile({
					count: 1, //默认100
					extension: extension,
					success: function (res) {
						next(res);
					},
					fail(err) {
						console.error(err);
						next(null);
					}
				});
				// #endif

				// #ifdef MP-WEIXIN
				uni.chooseMessageFile({
					count: 1, //默认100
					type: "file",
					extension: extension,
					success: async (res) => {
						next(res);
					},
					fail(err) {
						console.error(err);
						next(null);
					}
				});
				// #endif
			});
			if (!res) return;

			const tempFilePaths = res.tempFilePaths;
			let file = res.tempFiles[0];

			if (!extension.includes(file.name.slice(file.name.lastIndexOf(".") + 1))) {
				return tools.easyToast("请选择音频文件！");
			}
			let name = file.name.replace(/[^\u4e00-\u9fa5a-zA-Z0-9\.]/g, "");
			// if (!/^[\u4e00-\u9fa5a-zA-Z0-9\.\-]+$/.test(name)) {
			// 	return tools.easyToast("文件名不能包含符号，只能是文字或数字");
			// }
			if (file.size / 1024 / 1024 > this.uploadFileSize) {
				return tools.easyToast(`文件大小超过${this.uploadFileSize}M!`);
			}
			uni.showLoading({
				title: "上传中"
			});
			let matterValue = await new Promise(async (res) => {
				let tempCtx = uni.createInnerAudioContext();
				tempCtx.volume = 0;
				tempCtx.autoplay = true;
				tempCtx.src = file.path;
				tempCtx.onTimeUpdate((ctxres) => {
					console.log("tempCtx.onTimeUpdate", tempCtx.duration, ctxres);
					if (tempCtx.duration && tempCtx.duration != Infinity) {
						console.log("tempCtx.onCanplay1-1", tempCtx.duration);
						res(tempCtx.duration);
						tempCtx.stop();
					} else {
						console.log("tempCtx.onCanplay1-2", tempCtx.duration);
					}
				});
				tempCtx.onStop(() => {
					tempCtx.destroy();
				});
				tempCtx.onEnded(() => {
					tempCtx.destroy();
				});
			});
			console.log(matterValue);
			if (!matterValue) {
				tools.easyToast("stopTime && 添加失败！请重试~");
				return;
			}
			if (matterValue < 1) {
				return tools.easyToast("音频时长必须不少于1秒！");
			}
			let ossData = await api.postOSS({
				reqType: "",
				matName: name,
				payLoad: { matterValue: matterValue }
			});
			uni.hideLoading();
			if (!ossData) return;
			uni.showLoading({
				title: "音频解析中..."
			});
			let ress = await that.wx_getOSSApi_new(ossData, file.path, name);
			uni.hideLoading();
			if (!ress) return tools.easyToast("解析失败！");
			uni.showLoading({
				title: "音频解析中"
			});
			let result = await api.getAiworkobjv1ct({
				content: ress.src,
				obj: "a_obj"
			});
			uni.hideLoading();
			console.log(result);
			uni.setStorageSync("bigBreakEditInfo", {
				content: result.data
			});
			this.toPage("/pages/bigBreakEdit/bigBreakEdit");
		},

		// 暂未开放！
		noFn() {
			tools.easyToast("暂未开放！");
		},
		// wx小程序oss上传文件
		wx_getOSSApi_new(ossData, file, name) {
			const that = this;
			let res = ossData;
			function getUUID() {
				let keyStr = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";
				keyStr = "xxxxxxxx-6xxx";
				return keyStr.replace(/[xy]/g, (c) => {
					return (c === "x" ? (Math.random() * 16) | 0 : "r&0x3" | "0x8").toString(16);
				});
			}
			let url_name = "https://alleymall.oss-cn-guangzhou.aliyuncs.com";
			let key = res.data.dir + "/" + getUUID() + name;
			return new Promise((next) => {
				uni.uploadFile({
					url: url_name,
					filePath: file,
					name: "file",
					formData: {
						policy: res.data.policy,
						signature: res.data.signature,
						ossaccessKeyId: res.data.accessid,
						key: key,
						dir: res.data.dir,
						host: res.data.host,
						expire: res.data.expire,
						callback: res.data.callback
					},
					success: (uploadFileRes) => {
						let src = url_name + "/" + key;
						// console.log(src);
						// that.audioPlayerSrc = src;
						// console.log(response);
						next({ ...uploadFileRes, src });
					},
					fail(err) {
						console.log(err);
						next(false);
					}
				});
			});
		},

		// 提交
		async submit() {
			if (this.content.length == 0) {
				tools.easyToast("请输入链接地址");
				return;
			}
			uni.showLoading({
				title: "链接解析中"
			});
			let result = await api.getAiworkobjv1ct({
				content: this.content,
				obj: "tk_share"
			});
			uni.hideLoading();
			uni.setStorageSync("bigBreakEditInfo", {
				content: result.data
			});
			this.toPage("/pages/bigBreakEdit/bigBreakEdit");
		},
		// 文案失焦
		async contentBlur() {
			this.keyboardH = 0;
			console.log("文案失焦");
		},
		// 文案点击
		textareaTap() {
			this.keyboardH = 1;
			console.log("文案点击");
		},
		// 文案改变
		contentWatch_web(e) {
			// #ifndef MP-WEIXIN
			this.contentWatch(e);
			// #endif
		},
		// 文案改变
		contentWatch_wx(e) {
			// #ifdef MP-WEIXIN
			this.contentWatch(e);
			// #endif
		},
		// 文案改变
		contentWatch(e) {
			if (contentWatchTimer) {
				clearTimeout(contentWatchTimer);
			}
			contentWatchTimer = setTimeout(async () => {
				contentWatchTimer = null;
				this.content = e.detail.value;
			}, 200);
		},
		// 文案聚焦
		async contentFocus() {
			console.log("文案聚焦");
		},
		// 获取剪切板内容
		getClipboardData() {
			const that = this;
			uni.getClipboardData({
				success: function (res) {
					console.log("剪切板的内容：" + res.data);
					that.content = res.data;
				}
			});
		}
	},
	onLoad(opt) {
		this.initSystemInfo();
		this.initPageInfo(opt);
		this.getData();
	},
	created() {
		this.downloadBg();
	}
};
</script>

<style lang="scss">
::-webkit-scrollbar {
	width: 0vw !important;
	height: 0vw !important;
	display: none;
}

.BigBreak {
	width: 100vw;
	height: 100vh;
	position: relative;
	color: #fff;
	background: rgba(29, 29, 29, 1);

	.bgi {
		background: rgba(29, 29, 29, 1);
		position: absolute;
		z-index: 0;
		width: 100%;
		height: 100%;
		top: 0vw;
		left: 0vw;
	}

	.title-box {
		position: relative;
		display: flex;
		justify-content: space-between;
		align-items: center;

		.back {
			width: 8vw;
			height: 8vw;
			padding-left: 3vw;
			padding-top: 3vw;
		}

		.title {
			font-size: 36rpx;
			font-weight: 400;
			color: rgba(255, 255, 255, 1);
		}
	}
	.main {
		position: relative;
		height: 60vh;
		overflow: auto;
		box-sizing: border-box;
		padding: 2vw;
		display: flex;
		flex-direction: column;

		.main-tips {
			text-align: center;
			font-size: 1.25vh;
			color: #fff;
		}
		.cont-list {
			flex: 1;
			margin-top: 2vh;
			display: flex;
			flex-direction: column;
			overflow: auto;
			.item {
				background: rgba(126, 126, 126, 0.08);
				box-sizing: border-box;
				padding: 2vh 2vh;
				border-radius: 2.5vw;
				width: 88%;
				margin-bottom: 3vw;
				display: flex;
				flex-direction: column;
				margin: 0.86vh auto;

				&:last-child {
					flex: 1;
					display: flex;
					flex-direction: column;
					overflow: auto;
				}
				&.ac {
					border: 1vw solid #98c379;
				}

				.title {
					color: #fff;
					font-size: 1.86vh;
					font-weight: 700;
				}

				.cont-main {
					margin-top: 0.68vh;
					flex: 1;
					display: flex;
					flex-direction: column;
					overflow: auto;
					.textarea-box {
						width: 100%;
						flex: 1;
						position: relative;
						padding: 2.5vw;
						padding-top: 0;
						box-sizing: border-box;
						overflow: auto;
						.cont-textarea {
							width: 100%;
							height: 100%;
							font-size: 1.68vh;
							// max-height: 200px;
							color: rgba(255, 255, 255, 1);
						}
						.number {
							position: absolute;
							border-radius: 2vw;
							padding: 1vw 1.5vw;
							color: rgba(126, 126, 126, 1);
							background: rgba(255, 255, 255, 0.086);
							right: 2vw;
							bottom: 2vw;
						}
					}
					.btns {
						display: flex;
						justify-content: space-between;
						align-items: center;
						.btns-item {
							display: flex;
							justify-content: center;
							align-items: center;
							width: 46%;
							height: 5vh;
							border-radius: 2vw;
							border: 1px solid #09c7ae;
							font-weight: 700;
							font-size: 2vh;
							&.style1 {
								color: #09c7ae;
							}
							&.style2 {
								color: #000;
								background: #09c7ae;
							}
						}
					}
				}
			}
		}
		.opt-list {
			.item {
				width: 100%;
				margin-bottom: 6vw;
				.title {
					color: #fff;
					font-size: 3.68vw;
					font-weight: 100;
				}
				.slider {
				}
			}
		}
	}
}
</style>
